var chsPlayer = {
	player: null,
	duration: 0,
	init: function (url) {
		var videoObject = {
			container: '.myActive-play', //“#”代表容器的ID，“.”或“”代表容器的class
			variable: 'player', //该属性必需设置，值等于下面的new chplayer()的对象
			// loaded: 'loadedHandler',
			// poster: 'material/poster.jpg', //封面图片
			seek: 1,
			loop: true,
			autoplay: false,
			debug: false, //开启调试模式
			flashplayer: false, //强制使用flash
			live: false, //实时直播
			video: url //视频地址
		}
		this.player = new ckplayer(videoObject);
	},
	videoPlay: function () {
		//$(".jiankong").show();
		this.player.videoPlay();

	},
	videoPause: function () {
		this.player.videoPause();
	},
	videoClose: function () {
		this.player.videoClose();
	},
	changeVideo: function (videoUrl) {
		if (player == null) {
			return;
		}

		var newVideoObject = {
			container: '#video', //容器的ID
			variable: 'player',
			autoplay: true, //是否自动播放
			loaded: 'loadedHandler', //当播放器加载后执行的函数
			video: videoUrl
		}
		//判断是需要重新加载播放器还是直接换新地址

		if (player.playerType == 'html5video') {
			if (player.getFileExt(videoUrl) == '.flv' || player.getFileExt(videoUrl) == '.m3u8' || player.getFileExt(videoUrl) ==
				'.f4v' || videoUrl.substr(0, 4) == 'rtmp') {
				player.removeChild();

				player = null;
				player = new ckplayer();
				player.embed(newVideoObject);
			} else {
				player.newVideo(newVideoObject);
			}
		} else {
			if (player.getFileExt(videoUrl) == '.mp4' || player.getFileExt(videoUrl) == '.webm' || player.getFileExt(videoUrl) ==
				'.ogg') {
				player = null;
				player = new ckplayer();
				player.embed(newVideoObject);
			} else {
				player.newVideo(newVideoObject);
			}
		}
	}
}

var chsLive = {
	player: null,
	init: function (url) {
		if (this.player != null) {
			this.videoClear();
		}
		var videoObject = {
			container: '.activeLive-live-content', //“#”代表容器的ID，“.”或“”代表容器的class
			variable: 'player', //该属性必需设置，值等于下面的new chplayer()的对象
			autoplay: true,
			debug: false, //开启调试模式
			flashplayer: false, //强制使用flash
			live: true,
			video: url
		}
		this.player = new ckplayer(videoObject);
	},
	videoPlay: function () {
		this.player.videoPlay();
	},
	videoPause: function () {
		this.player.videoPause();
	},
	videoClear: function () {
		this.player.videoClear();
	}
}

var sdkappid = "1400200106";
var userid = "chs_im_user_001";
var userSig = "eJxNjVFvgjAUhf9Ln5d5QYFmyR6QsIjBhY0ysqcGaat3DiRt2dRl-11kmuzxnu*c7-4Qlub3Rux41XUoyANxZgAugAM*uRuhPHSoJa*UlfrCPc8bOFzpOOOV5VN9Wd9ii438K1MIaBC41xyFbC0qHFX11nBseG*k5sPHm7Gu931ruT128p-R4Ga4VnERJU-UD46ZLA*Rel*WHyn9qlmTw3IXikzoTeYyMX*ZY5KqIsQ4NJlZy5PDRNk70Xex9Z9PKz9ZfCro9m0-qfLXeEHZup2*wSP5PQOPCVPJ";
var roomId = "321183";
var privateMapKey = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg0946uIGP+iuKJ8ZfiOQlERw0ytou6FgH2AhGyB7FlFihRANCAASBZA/uAalL4sXLiDceTw8KCz1JYHcdNxoLkIqdTjTxI++toRjbZmF7euwC9RuNcJyjCslYmzObVdlbLtwo3tE5";
var videoName;
//获取签名
function getUserSig(idList, nameList) {
	initRTC({
		"userId": userid,
		"userSig": userSig,
		"privateMapKey": privateMapKey,
		"sdkappid": sdkappid,
		"closeLocalMedia": true,
		"accountType": 14418,
		"roomid": roomId
	});
	infoWindow.close()
	$(".mask").show();
	setTimeout(function () {
		startRTC();
	}, 2000)
	for (var i = 0; i < idList.length; i++) {
		videoName = nameList[i];
		onSendMsg(roomId, idList[i]);
	}
}

function initRTC(opts) {
	// 初始化
	window.RTC = new WebRTCAPI({
		"useCloud": "1",
		"debug": {
			log: true
		},
		"userId": opts.userId,
		"userSig": opts.userSig,
		"sdkAppId": opts.sdkappid
	});
	RTC.createRoom({
		roomid: opts.roomid * 1,
		privMap: 255
	}, function () {
		if (opts && opts.closeLocalMedia) return;
		gotStream({
			audio: true,
			video: true
		}, function (stream) {
			RTC.startRTC({
				stream: stream,
				role: 'user'
			});
		})
	});
	// 远端流新增/更新
	RTC.on("onRemoteStreamUpdate", onRemoteStreamUpdate)
	// 本地流新增
	RTC.on("onLocalStreamAdd", onLocalStreamAdd)
	// 远端流断开
	RTC.on("onRemoteStreamRemove", onRemoteStreamRemove)
	// 重复登录被T
	RTC.on("onKickout", onKickout)
	// 服务器超时
	RTC.on("onRelayTimeout", onRelayTimeout)
	// just for debugging
	// RTC.on("*",function(e){
	// console.debug(e)
	// });
	RTC.on("onErrorNotify", function (info) {
		console.error(info)
		if (info.errorCode === RTC.getErrorCode().GET_LOCAL_CANDIDATE_FAILED) {
			// alert( info.errorMsg )
		}
	});
	RTC.on("onStreamNotify", function (info) {
		// console.warn('onStreamNotify', info)
	});
	RTC.on("onWebSocketNotify", function (info) {
		// console.warn('onWebSocketNotify', info)
	});
	RTC.on("onUserDefinedWebRTCEventNotice", function (info) {
		// console.error( 'onUserDefinedWebRTCEventNotice',info )
	});
}

function gotStream(opt, succ) {
	RTC.getLocalStream({
		video: true,
		audio: true,
		videoDevice: opt.videoDevice,
		// 如需指定分辨率，可以在attributes中增加对width和height的约束
		// 否则将获取摄像头的默认分辨率
		// 更多配置项 请参考 接口API
		// https://cloud.tencent.com/document/product/647/17251#webrtcapi.getlocalstream
		// attributes:{
		//     width:640,
		//     height:320
		// }
	}, function (info) {
		var stream = info.stream;
		succ(stream)
	});
}

function startRTC() {

	RTC.startRTC(0, function (info) {
		//onSendMsg("123",userId);
		// console.debug(info)
	}, function (info) {
		// console.debug(info)
	});
}

function onRelayTimeout(msg) {
	//alert("onRelayTimeout!" + (msg ? JSON.stringify(msg) : ""));
}
var nameList = ["", "", ""];
var index = 0;
var name;

function createVideoElement(id, isLocal) {
	// 	if (index > 2) {
	// 		index = 0;
	// 	}
	// 	name = nameList[index];
	// 	index++;
	var videoDiv = document.createElement("div");
	videoDiv.innerHTML = '<video id="' + id + '" autoplay ' + (isLocal ? 'muted' : '') +
		' playsinline  ></video><span class="smallTitle">' + videoName + '</span>';
	document.querySelector("#remote-video-wrap").appendChild(videoDiv);

	return document.getElementById(id);
}

function onLocalStreamAdd(info) {
	if (info.stream && info.stream.active === true) {
		// 						var id = "local";
		// 						var video = document.getElementById(id);
		// 						if (!video) {
		// 							createVideoElement(id, true);
		// 						}

		var video = document.getElementById("local01");
		video.srcObject = info.stream;
		video.muted = true
		video.autoplay = true
		video.playsinline = true
	}
}


function onRemoteStreamUpdate(info) {

	// console.debug(info)
	if (info.stream && info.stream.active === true) {
		console.error('info', info)
		var id = info.videoId;
		var video = document.getElementById(id);
		if (!video) {
			video = createVideoElement(id);
		}
		setTimeout(function () {
			video.srcObject = info.stream;
			video.muted = false
			video.autoplay = true
			video.playsinline = true
			video.play();
		}, 50)
	} else {
		// console.log('欢迎用户' + info.userId + '加入房间');
	}
}


function onRemoteStreamRemove(info) {
	// console.log(info.userId + ' 断开了连接');
	console.log(info)
	var videoNode = document.getElementById(info.videoId);
	if (videoNode) {
		videoNode.srcObject = null;
		document.getElementById(info.videoId).parentElement.remove();

	}
}

function onKickout() {
	//alert("on kick out!");
}

function onWebSocketClose() {
	RTC.quit();
}

function quitRTC() {
	//chsPlayer.videoPlay();
//	RTC.quit();
	$(".mask").hide();
//	initRTC({
//		"userId": userId,
//		"userSig": userSig,
//		"privateMapKey": privateMapKey,
//		"sdkappid": sdkappid,
//		"closeLocalMedia": true,
//		"accountType": 14418,
//		"roomid": roomId
//	});
}


function hoverPlay() {
	$(".videoBox").hover(function () {
		$('#myVideo').attr("controls", "controls");
		$('.chooseVideo').css('visibility', 'visible');
	},
		function () {
			$('#myVideo').removeAttr("controls");
			$('.chooseVideo').css('visibility', 'hidden');
		})
}